/**
 * mwe2644 neu 05.12.2011
 */
package fhv.at.imageprocessing.viewImage;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.io.Serializable;

import javax.media.jai.PlanarImage;

import fhv.at.imageprocessing.ImageChangedEvent;
import fhv.at.imageprocessing.ImageChangedListener;
import fhv.at.imageprocessing.ImageHelper;
import fhv.at.imageprocessing.ImageNeededEvent;

/**
 * View image bean. Uses a canvas to paint the picture
 * 
 * @author phru
 * 
 */
public class ViewImage extends Canvas implements ImageChangedListener,
		Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private PlanarImage planarImage;
	private final ImageHelper imageHelper;

	public ViewImage() {
		int maxParents = 1;
		imageHelper = new ImageHelper(maxParents, this);
		setSize(50, 50);
	}

	/* Eigentliche Bildbearbeitung */
	@Override
	public void manipulateImage() {
		// Groesse anpassen
		if (planarImage != null) {
			setSize(planarImage.getWidth(), planarImage.getHeight());
		}
		repaint();
	}

	@Override
	public void paint(Graphics g) {

		// Rand zeichnen
		g.setColor(Color.black);
		g.drawRect(0, 0, getSize().width - 1, getSize().height - 1);

		// Bild anzeigen
		if (planarImage != null) {
			g.drawImage(planarImage.getAsBufferedImage(), 0, 0, this);
		}
	}

	/* Implementation fur Eventregistrierung */
	@Override
	public void addImageChangedListener(ImageChangedListener icl) {
		imageHelper.addImageChangedListener(icl);
	}

	@Override
	public void removeImageChangedListener(ImageChangedListener icl) {
		imageHelper.removeImageChangedListener(icl);
	}

	@Override
	public void addImageNeededListener(ImageChangedListener icl) {
		imageHelper.addImageNeededListener(icl);
	}

	@Override
	public void removeImageNeededListener(ImageChangedListener icl) {
		imageHelper.removeImageNeededListener(icl);
	}

	/* Implementation fur ImageChangedListener */
	@Override
	public void imageValueChanged(ImageChangedEvent ice) {
		System.out.println(getClass().getSimpleName() + ": imageValueChanged");
		planarImage = imageHelper.getPlanarImage(ice);
		manipulateImage();
	}

	@Override
	public void imageNeeded(ImageNeededEvent ice) {
		System.out.println(getClass().getSimpleName() + ": imageNeeded");
		imageHelper.fireImageChangedEvent();
		// imageHelper.fireImageChangedEvent(ice);
	}

	@Override
	public ImageChangedListener getRefFromSource() {
		return this;
	}

	@Override
	public PlanarImage getPlanarImage() {
		return planarImage;
	}

}
